package v4

import (
	"fmt"
	"log"
	"mindonmap/pkgs/e"
	"mindonmap/pkgs/util"
	"mindonmap/validation"
	"net/http"
	"path/filepath"
	"strings"

	"github.com/golang-jwt/jwt/v4"

	"time"

	"github.com/gin-gonic/gin"
)

type mindImage struct {
	Acid   string `json:"acid"`
	Mindid string `json:"mindid"`
}

func parseToken(tokenString string) (*jwt.Token, jwt.MapClaims, error) {
	var mySigningKey = []byte("mind")
	// 解析token
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// 确保token的签名算法是HS256
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return mySigningKey, nil
	})

	if err != nil {
		return nil, nil, err
	}

	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok || !token.Valid {
		return nil, nil, fmt.Errorf("token is invalid")
	}

	return token, claims, nil
}
func UploadFile(c *gin.Context) {
	mindid := c.PostForm("mindid")

	var strUserid string
	// 从Header中获取token
	authHeader := c.GetHeader("Authorization")
	bearerToken := strings.TrimPrefix(authHeader, "Bearer ")
	_, claims, err := parseToken(bearerToken)
	Userid := claims["userId"].(string)
	if err != nil {
		strUserid = "anonymous"
	} else {
		strUserid = Userid
	}

	var JsondataInfo = &mindImage{
		Acid:   claims["userId"].(string),
		Mindid: mindid,
	}
	valid := validation.Validation{}
	valid.Required(JsondataInfo.Mindid, "mindid").Message("不能为空")

	code := e.SUCCESS
	data := make(map[string]interface{})
	if !valid.HasErrors() {

		fileHeader, err := c.FormFile("file")
		f, err := fileHeader.Open()
		if err != nil {
			code = e.INVALID_PARAMS
			fmt.Println(err)
		}
		var size = fileHeader.Size
		buffer := make([]byte, size)
		f.Read(buffer)

		now := time.Now()
		fileStrTime := now.Format("2006-01-02")
		ext := filepath.Ext(fileHeader.Filename)
		uuidStr, _ := util.UUIDv4()
		newFilename := uuidStr + ext
		Filename := fileStrTime + "/" + strUserid + "/" + JsondataInfo.Mindid + "/" + newFilename
		data["url"] = util.WriteFileR2_image(Filename, size, buffer)

	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// Removefilte 删除文件
func Removefile(c *gin.Context) {
	path := c.PostForm("path")
	code := e.SUCCESS
	filestatus := util.DeleteFileObject_R2_single(path)
	if !filestatus {
		code = e.ERROR_AUTH_PERMISSION
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": "",
	})
}
